package com.cn.lp.export.client.base.utils;

import com.cn.lp.export.client.base.BeanConvertException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 请描述你的文件
 *
 * @author wuqirong
 * @date 2020-10-21
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */
public class BeanUtils {

    /**
     * Logging for this instance
     */
    private static final Log logger = LogFactory.getLog(BeanUtils.class);

    /**
     * 将bean转化为Map，将getX()的属性提取到Map中
     *
     * @param bean
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     */
    public static Map<String, Object> beanToMap(Object bean) {
        try {
            if (bean == null) {
                return Collections.emptyMap();
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Describing bean: " + bean.getClass().getName());
            }
            final Map<String, Object> description = new HashMap<>();
            PropertyUtilsBean propertyUtilsBean = BeanUtilsBean.getInstance().getPropertyUtils();
            final PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(bean);
            for (PropertyDescriptor descriptor : descriptors) {
                final String name = descriptor.getName();
                // 剔除没有get方法的属性和getClass()方法
                if (propertyUtilsBean.getReadMethod(descriptor) != null && !name.equals("class")) {
                    Object value = propertyUtilsBean.getNestedProperty(bean, name);
                    if (value != null) {
                        description.put(name, value);
                    }
                }
            }
            return description;
        } catch (Exception e) {
            throw new BeanConvertException(e);
        }
    }
}
